﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Threading;
using System.Web.SessionState;

namespace jQuery.UI.Progressbar
{
    public partial class Progressbar : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Session["OPERATION_PROGRESS"] = 0;
        }

        /// <summary>
        /// PageMethod for triggering long running operation
        /// </summary>
        /// <returns></returns>
        [System.Web.Services.WebMethod(EnableSession = true)]
        public static object Operation()
        {
            HttpSessionState session = HttpContext.Current.Session;

            //Separate thread for long running operation
            ThreadPool.QueueUserWorkItem(delegate
            {
                int operationProgress;
                for (operationProgress = 0; operationProgress <= 100; operationProgress = operationProgress + 2)
                {
                    session["OPERATION_PROGRESS"] = operationProgress;
                    Thread.Sleep(1000);
                }
            });

            return new { progress = 0 };
        }

        /// <summary>
        /// PageMethod for reporting progress
        /// </summary>
        /// <returns></returns>
        [System.Web.Services.WebMethod(EnableSession = true)]
        public static object OperationProgress()
        {
            int operationProgress = 0;

            if (HttpContext.Current.Session["OPERATION_PROGRESS"] != null)
                operationProgress = (int)HttpContext.Current.Session["OPERATION_PROGRESS"];

            return new { progress = operationProgress };
        }
    }
}